package com.es;

import com.es.util.HighLevelClient;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.client.sniff.SniffOnFailureListener;
import org.elasticsearch.client.sniff.Sniffer;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.*;
import java.util.stream.Stream;

public class RestClientDemo {

    public static void main(String[] args) throws Exception{
//        createIndex();
//        getIndex();
//        insertData();
        insertBatchData();
    }

    public static void createIndex() throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));

        CreateIndexRequest request = new CreateIndexRequest("twitter");
//        request.settings(Settings.builder()
//                .put("index.number_of_shards", 3)
//                .put("index.number_of_replicas", 2)
//        );

//        request.alias(new Alias("twitter_alias").filter(QueryBuilders.termQuery("user", "kimchy")));
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse.isAcknowledged());
        client.close();
    }

    public static void getIndex() throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));

        GetIndexRequest request = new GetIndexRequest("twitter");

       GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);
        Stream.of(getIndexResponse.getIndices()).forEach(p -> System.out.println(p));

//        MappingMetadata indexMappings = getIndexResponse.getMappings().get("index");
//        Map<String, Object> indexTypeMappings = indexMappings.getSourceAsMap();
//        List<AliasMetadata> indexAliases = getIndexResponse.getAliases().get("index");
//        String numberOfShardsString = getIndexResponse.getSetting("index", "index.number_of_shards");
//        Settings indexSettings = getIndexResponse.getSettings().get("index");
//        Integer numberOfShards = indexSettings.getAsInt("index.number_of_shards", null);
//        TimeValue time = getIndexResponse.getDefaultSettings().get("index")
//                .getAsTime("index.refresh_interval", null);
        client.close();
    }

    public static void insertData() throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));

        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("user", "kimchy");
        jsonMap.put("postDate", new Date());
        jsonMap.put("message", "trying out Elasticsearch");
        IndexRequest indexRequest = new IndexRequest("twitter")
                .id("1").source(jsonMap);
        indexRequest.opType(DocWriteRequest.OpType.CREATE);
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.getResult());
        client.close();
    }

    public static void insertBatchData() throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));

        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest("product").id("5")
                .source(XContentType.JSON,"name", "小米风扇", "desc", "为发烧而生", "price", 9999, "date", "2024-11-15", "tags", new String[]{"性价比", "超值", "划算"}));
        request.add(new IndexRequest("product").id("6")
                .source(XContentType.JSON,"name", "小米风扇", "desc", "为发烧而生", "price", 9999, "date", "2024-11-15", "tags", new String[]{"性价比", "超值", "划算"}));
        request.add(new IndexRequest("product").id("7")
                .source(XContentType.JSON,"name", "小米风扇", "desc", "为发烧而生", "price", 9999, "date", "2024-11-15", "tags", new String[]{"性价比", "超值", "划算"}));
//        request.add(new DeleteRequest("product").id("4"));
        BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);

        for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) {
            DocWriteResponse itemResponse = bulkItemResponse.getResponse();

            switch (bulkItemResponse.getOpType()) {
                case INDEX:
                case CREATE:
                    IndexResponse indexResponse = (IndexResponse) itemResponse;
                    System.out.println(indexResponse.status());
                    break;
                case UPDATE:
                    UpdateResponse updateResponse = (UpdateResponse) itemResponse;
                    break;
                case DELETE:
                    DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
            }
        }

        client.close();
    }

    public static void sniff() {
        SniffOnFailureListener sniffOnFailureListener =
                new SniffOnFailureListener();

        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200))
                .setFailureListener(sniffOnFailureListener)
                .build();

        Sniffer sniffer = Sniffer.builder(restClient)
                .setSniffIntervalMillis(60000)
                .setSniffAfterFailureDelayMillis(30000)
                .build();
        sniffOnFailureListener.setSniffer(sniffer);
    }

}
